package com.etoak.common.web.context;

import com.etoak.common.jwt.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.HttpHeaders;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Map;

public class LoginContext {
    // 获取当前登录用户id
    public static String getUserId(){
        HttpServletRequest request = getRequest();
        String jwt = request.getHeader(HttpHeaders.AUTHORIZATION);
        Map<String, Object> claimsMap = JwtUtil.parse(jwt);
        return claimsMap.get("id").toString();
    }

    private static HttpServletRequest getRequest() {
        ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        return attributes.getRequest();
    }
}
